const {
  base_url
} = require('./config');

const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return `${[year, month, day].map(formatNumber).join('/')} ${[hour, minute, second].map(formatNumber).join(':')}`
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : `0${n}`
}

/**
 * 表单验证 验证表单是否通过 并把有问题的字段挑选出来
 * @param form { Object } 需要验证的表单数据
 * @param rules { Object } 需要验证的表单规则
 */
exports.validate = (form = {}, rules = {}) => {
  const errors = {}; // 用来收集错误信息的
  //  遍历 rules 找出 所有有问题，未通过验证的字段
  for (let key in rules) {
    const _value = form[key];
    const items = rules[key]; //  每一个字段可能对应多条验证规则

    // 如果有错，将其记录，退出进行下一轮循环，保证只有一个错误提示显示
    for (let item of items) {
      if (item.empty) { //  判断 该字段是否是必填  empty
        isEmpty(_value) && (errors[key] = item.msg);
      } else if (item.rule) { //  验证匹配规则
        !isAccess(_value, item.rule) && (errors[key] = item.msg);
      }

      //   如果 已经记录了错误 则 退出本字段的验证，对下一个字段进行验证
      if (errors[key]) break;
    }
  }

  //  通过 判断 errors 里面的数据是否为空 - 来判断是否验证通过
  return isEmptyObject(errors) ? null : errors;
}

//  判断 value 的值是否是一个空值
function isEmpty(val = '') {
  return val.length > 0 ? false : true;
}

//  判断 value 的值是否通过规则验证
function isAccess(val, rule) {
  if (dataType(rule) === 'function') {
    return rule(val);
  }
}

//  判断数据类型
function dataType(val = '') {
  const type = Object.prototype.toString.call(val);
  switch (type) {
    case '[object Function]':
      return 'function';
  }
}

//  判断是否是一个空对象
function isEmptyObject(obj) {
  return JSON.stringify(obj) == "{}";
}

//  全局属性
let toast = null;
let actionsheet = null;
let datepicker = null;
let cityselect = null;

exports.setToast = (element) => {
  toast = element;
}

exports.getToast = () => {
  return toast;
}

exports.setActionSheet = (element) => {
  actionsheet = element;
}

exports.getActionSheet = () => {
  return actionsheet;
}

exports.setDatePicker = (element) => {
  datepicker = element;
}

exports.getDatePicker = () => {
  return datepicker;
}

exports.setCitySelect = (element) => {
  cityselect = element;
}

exports.getCitySelect = () => {
  return cityselect;
}



//  初始化 时间 - 让其保持当前的时间
exports.initPicker = () => {
  const date = new Date();
  const year = date.getFullYear() - 1000;
  const month = date.getMonth();
  const day = date.getDate() - 1;
  const hour = date.getHours();
  const min = date.getMinutes();
  const second = date.getSeconds();

  return [year, month, day, hour, min, second];
}

exports.isFinished = function (total, num) {
  return total >= num ? false : true;
}

/*** 时间格式处理 去掉分钟
 * @param arr { Array } [ year, month, day ]
 */
exports.formatTime2 = (str) => {
  const date = new Date(str);
  const year = date.getFullYear();
  const month = date.getMonth() + 1;
  const day = date.getDate();
  return year + '-' + addZero(month) + '-' + addZero(day);
}

//  时间数组 格式化
exports.formatTime3 = (arr) => {
  if (arr.length > 0) {
    return `${ arr[0] }-${ addZero( arr[1] ) }-${ addZero( arr[2] ) } ${addZero(arr[3])}:${addZero(arr[4])}:${addZero(arr[5])}`;
  }
  return ''
}

//  倒计时
exports.countdownFn = (str) => {
  const end = new Date(str);
  const now = new Date();
  const temp = (end - now) / 1000;

  if (temp <= 0) {
    return -1;
  }

  const min = parseInt(temp / 60 % 60);
  const hour = parseInt(temp / 60 / 60 % 24);
  const day = parseInt(temp / 60 / 60 / 24);

  return `${ day }天${ addZero( hour ) }小时${ addZero( min ) }分`;
}

function addZero(data) {
  return data < 10 ? '0' + data : data;
}

//  截取字符串
exports.sliceString = (str = '', num) => {
  const len = str.length;

  if (len === 0) {
    return ''
  } else if (len > num) {
    const result = str.slice(0, num);
    return result + '...';
  } else {
    return str;
  }
}


//  弹窗封装
exports.myToast = (icon, title) => {
  wx.showToast({
    title,
    icon,
    duration: 1000
  })
}

//  获取性别字典项， 主要是用来首次注册使用的
exports.genderDists = ['未设置', '男', '女'];

//  将临时文件转成 base64
exports.toBase64 = (url, type) => {
  console.log('196', url);
  return new Promise((resolve, reject) => {
    wx.getFileSystemManager().readFile({
      filePath: url, //选择图片返回的相对路径
      encoding: 'base64', //编码格式
      success: res => {
        resolve({
          filename: url,
          data: res.data
        })
      },
      fail: res => reject(res.errMsg)
    })
  })
}

//  处理 base64 文件格式
exports.joinBase64 = (str) => {
  return str.replace(':base64', ';base64');
}

/**
 * 根据身份证号获取性别
 * @param idCard
 */
exports.getSex = (idCard) => {
  if (parseInt(idCard.slice(-2, -1)) % 2 == 1) {
    return '1'; //  man
  } else {
    return '2'; //  woman
  }
}


//处理富文本框图片没有地址的
exports.replaceImg = (content) => {
  var imgInfo = /<img [^>]*src=['"]([^'"]+)[^>]*>/g; // img 标签取src里面内容的正则
  var allImg = content.match(imgInfo); // 取到所有img标签 放到数组allImg里面
  if (allImg) { //可能没有匹配
    for (var i = 0; i < allImg.length; i++) {
      var srcImg = allImg[i].replace(imgInfo, '$1'); //取src面的内容
      if (srcImg.slice(0, 4) == 'http' || srcImg.slice(0, 5) == 'https') {
        //匹配http，https，看需求是否处理
      } else {
        //修改富文本字符串内容 img标签src 相对路径改为绝对路径
        content = content.replace(new RegExp(srcImg, 'g'), base_url + srcImg);
        // 正则表达式匹配img标签的style属性
        var regex = /<img[^>]*style="([^"]*)"[^>]*>/gi;

        // 替换函数，这里我们只是简单地删除style属性
        function replaceStyle(match) {
          return match.replace(/style="[^"]*"/i, 'style="max-width:100%;height:auto"');
        }

        // 使用replace方法和正则表达式进行替换
        content = content.replace(regex, replaceStyle);
      }
    }
  }

  return content
}


//  基本时间数组
const yearsArr = [];
for (let i = 1000; i <= 3000; i++) {
  yearsArr.push(i)
}
exports.yearsArr = yearsArr;

const monthsArr = [];
for (let i = 1; i <= 12; i++) {
  monthsArr.push(i)
}
exports.monthsArr = monthsArr;

const daysArr = [];
for (let i = 1; i <= 31; i++) {
  daysArr.push(i)
}
exports.daysArr = daysArr;

const hoursArr = [];
for (let i = 0; i < 24; i++) {
  hoursArr.push(i)
}
exports.hoursArr = hoursArr;

const minsArr = [];
for (let i = 0; i < 60; i++) {
  minsArr.push(i)
}
exports.minsArr = minsArr;

const secondsArr = [];
for (let i = 0; i < 60; i++) {
  secondsArr.push(i)
}
exports.secondsArr = secondsArr;


exports.readFile = (filename) => {
  return new Promise(( resolve, reject ) => {
    wx.getFileSystemManager().readFile({  //读取文件
      filePath: '/packageA/utils/base64/' + filename,
      encoding: 'utf-8',
      success: res => {
        resolve( res.data );
      },
      fail: reject
    })
  })
}